/*******************************************************
> Copyright (C) 2024 ==IOT== All rights reserved.
> File Name: likangnurse_side.c
> Author: lv1
> Website:www.lv1.org
> Created Time: 2024年12月04日 星期三 14时12分01秒
***************************************************/

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <mysql/mysql.h>
//#include "cJSON.h"

typedef struct Nur
{
	char nursename[20];
	char passwd[20];
}NU;

int repeat(MYSQL *mysql, NU nur);

//void allnurses(MYSQL *mysql);
int main()
{
	
	MYSQL mysql;
	mysql_init(&mysql);
	MYSQL *flag;
	flag = mysql_real_connect(&mysql,"localhost","root","1","care",0,NULL,0);
	if(flag == NULL)
	{
		printf("%s\n",mysql_error(&mysql));
	}
	
	NU nur = {0};
	printf("input nursename: \n");
	scanf("%s",nur.nursename);
	printf("input passwd: \n");
	scanf("%s",nur.passwd);
	int all =repeat(&mysql,nur);
	if(all == 0)
	{
		printf("注册成功\n");
	}
	else
	{
		printf("注册失败，请重新输入\n");
	}
		
	//删除
	char nurse_name[20] = {0};
	printf("input delete staff: \n");
	scanf("%s",nurse_name);
	char del[128]={0};
	sprintf(del,"delete from nurse where nursename = '%s'",nurse_name);
	mysql_query(&mysql,del);
	
	printf("用户已删除\n");
	
	//allnurses(&mysql);
	
	mysql_close(&mysql);
}

int repeat(MYSQL *mysql, NU nur)
{
	char buf[128]={0};
	sprintf(buf,"select * from nurse where nursename='%s'",nur.nursename);
	int ret = mysql_real_query(mysql,buf,strlen(buf));
	if(ret != 0)
	{
		printf("select failed:%s",mysql_error(mysql));	
		return -1;
	}
	MYSQL_RES* res = mysql_store_result(mysql);
	int rows = mysql_num_rows(res);
	//没有结果集
	if(rows == 0 )
	{
		//入库操作	
		memset(buf,0,sizeof(buf));
		sprintf(buf,"insert into nurse (nursename,passwd) values ('%s','%s')",nur.nursename,nur.passwd);

		ret = mysql_real_query(mysql,buf,strlen(buf));
		if(ret != 0)
		{
			printf("insert failed:%s",mysql_error(mysql));	
			return -1;	
		}
	}
	else
	{
		printf("用户名已存在，请重新输入\n");	
		return -1;
	}

	mysql_free_result(res);
	return 0;
}
/*
int register_nurse(MYSQL *mysql, NU nur)
{
    return repeat(mysql, nur);
}
void allnurses(MYSQL *mysql)
{
    char *query = "select *from nurse";
    if (mysql_query(mysql, query)) {
        fprintf(stderr, "查询失败: %s\n", mysql_error(mysql));
    }

    MYSQL_RES *result = mysql_store_result(mysql);
    if (result == NULL) {
        fprintf(stderr, "结果集为空: %s\n", mysql_error(mysql));
   }

    MYSQL_ROW row;
    while ((row = mysql_fetch_row(result))) {
        printf("Nurse Name: %s, Password: %s\n", row[0], row[1]);
    }

    mysql_free_result(result);
}
*/
